package itbour.onetouchshow.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.andview.adapter.BaseRecyclerHolder;
import com.lsjr.utils.NetUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import itbour.onetouchshow.App;
import itbour.onetouchshow.AppCache;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.userinfo.FeedBackActivity;
import itbour.onetouchshow.activity.web.CommWebActivity;
import itbour.onetouchshow.base.BaseRefreshAdapter;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.listener.MyRyItemListener;
import itbour.onetouchshow.utils.FileUtils;
import itbour.onetouchshow.utils.GetFileSizeUtil;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.sharedpreference.PreferencesHelper;

/**
 * Created by onetouch on 2017/11/30.
 */

@SuppressLint("ValidFragment")
public class SettingActivity extends MVPBaseActivity {

    @BindView(R.id.id_login_out)
    TextView idLoginOut;
    SettingAdapter settingAdapter;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    private List<String> mdata = new ArrayList<>();

    private SensorManager mSensorManager;
    private Sensor mAccelerometerSensor;
    private SensorEventListener sensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            int type = event.sensor.getType();

            if (type == Sensor.TYPE_ACCELEROMETER) {
                //获取三个方向值
                float[] values = event.values;
                float x = values[0];
                float y = values[1];
                float z = values[2];

                if ((Math.abs(x) > 17 || Math.abs(y) > 17 || Math
                        .abs(z) > 17)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(getViewContext(), ServiceAddressActivity.class);
                            startActivity(intent);
                        }
                    });

                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    @Override
    protected void initView() {

        initRecycleView();

    }

    public void initRecycleView() {
        //  mdata.add("意见反馈");
        mdata.add("关于我们");
        mdata.add("用户协议");
        mdata.add("清除缓存");
        settingAdapter = new SettingAdapter(getApplicationContext(), mdata, R.layout.item_me_frag);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()) {
            @Override
            public boolean canScrollVertically() {
                return true;
            }
        });

        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            private int mSpace = UIUtils.dip2px(10);

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int childCount = parent.getChildCount();
                int pos = parent.getChildAdapterPosition(view);
                outRect.left = 0;
                outRect.top = 0;
                outRect.bottom = 0;
                if (pos == 3) {
                    outRect.top = mSpace;
                } else {
                    if (pos != (childCount - 1)) {
                        outRect.right = mSpace;
                    } else {
                        outRect.right = 0;
                    }
                }

            }

        });
        recyclerView.setAdapter(settingAdapter);

        settingAdapter.setOnItemClickListener(new MyRyItemListener<String>() {
            @Override
            public void onItemSelect(String o) {
                if (o.equals("意见反馈")) {
                    openActivity(FeedBackActivity.class);
                    return;
                } else if (o.equals("清除缓存")) {
                    long cacheSize = GetFileSizeUtil.getFileSize(new File(AppCache.getInstance().mAppDir));
                    // com.shuyu.gsyvideoplayer.utils.FileUtils.deleteFiles();
                    FileUtils.recursionDeleteFile(new File(AppCache.getInstance().mAppDir));
                    T_.showCustomToast("清除缓存成功");
                    return;
                    //T_.showToastReal("缓存大小"+	GetFileSizeUtil.formatFileSize(cacheSize)+"M");
                    // oivSetting.setRightText("缓存大小"+	GetFileSizeUtil.formatFileSize(cacheSize)+"M");
                }
                if (NetUtils.isConnected(UIUtils.getContext())) {
                    if (o.equals("关于我们")) {
                        Bundle bundle = new Bundle();
                        bundle.putString(AppConst.WEBTYPE, AppConst.TYPE_ABOUT_ME);
                        openActivity(CommWebActivity.class, bundle);
                    } else if (o.equals("用户协议")) {
                        Bundle bundle = new Bundle();
                        bundle.putString(AppConst.WEBTYPE, AppConst.TYPE_USERAGREEMENT);
                        openActivity(CommWebActivity.class, bundle);
                    }
                } else {
                    T_.showCustomToast("请检查网络");
                }

            }
        });
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        setTitleText("设置");

        if (getPacketIsDebug()) {
            //获取 SensorManager 负责管理传感器
            mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
            if (mSensorManager != null) {
                //获取加速度传感器
                mAccelerometerSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
                if (mAccelerometerSensor != null) {
                    mSensorManager.registerListener(sensorEventListener, mAccelerometerSensor, SensorManager.SENSOR_DELAY_UI);
                }
            }

        }
    }

    @Override
    protected void onPause() {
        if (getPacketIsDebug()) {
            if (mSensorManager != null) {
                mSensorManager.unregisterListener(sensorEventListener);
            }
        }
        super.onPause();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (getPacketIsDebug()) {
            if (mSensorManager != null) {
                mSensorManager.registerListener(sensorEventListener, mAccelerometerSensor, SensorManager.SENSOR_DELAY_UI);
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {

    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {

    }

    private boolean getPacketIsDebug() {
        ApplicationInfo appInfo = null;
        boolean enable = false;
        try {
            appInfo = this.getPackageManager()
                    .getApplicationInfo(getPackageName(),
                            PackageManager.GET_META_DATA);
            enable = appInfo.metaData.getBoolean("isDebug");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return enable;
    }

    @OnClick(R.id.id_login_out)
    public void onViewClicked() {
        new OneToucDialog.Builder(this)
                .content("确定退出")
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                //complexDialogFrag.dismiss();
                App.loginOut();
                finish();
                PreferencesHelper.remove(AppConst.KEY_APP_SHARE_CONTENT);
                PreferencesHelper.remove(AppConst.KEY_APP_SHARE_TITLE);

                PreferencesHelper.remove(AppConst.KEY_CUSTOM_SHARE_TITLE);
                PreferencesHelper.remove(AppConst.KEY_CUSTOM_SHARE_CONTENT);
            }
        })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击确定");
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false)
                .show();


    }

    public class SettingAdapter extends BaseRefreshAdapter<String> {

        public SettingAdapter(Context context, List<String> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        @Override
        protected void convert(BaseRecyclerHolder baseRecyclerHolder, String var2, int var3) {
            TextView tv_name = baseRecyclerHolder.getView(R.id.tv_name);
            tv_name.setText(var2);
            baseRecyclerHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener != null) {
                        onItemClickListener.onItemSelect(var2);
                    }
                }
            });

        }
    }

}
